package ren.nearby.http.utils.util;

import android.content.Context;
import android.text.TextUtils;

import com.google.gson.Gson;
import com.google.gson.GsonBuilder;
import com.orhanobut.logger.Logger;

import org.json.JSONArray;
import org.json.JSONObject;

import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.Map;

import javax.inject.Inject;

/**
 * 数据请求封装类
 * Created by Administrator on 2018/5/10 0010.
 */

public class ReqMessage {


    public static String toJsonStr(String json) {
        String result = "1";
        try {
            JSONObject js = new JSONObject(json);
            result = js.getString("result");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    public static String toJsonStr2(String json) {
        String result = "1";
        try {
            JSONObject js = new JSONObject(json);
            JSONObject jsonObject = js.getJSONObject("msg");
            result = jsonObject.getString("result");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    private static volatile ReqMessage instance;

    public static ReqMessage getInstance() {
        if (instance == null) {
            synchronized (ReqMessage.class) {
                if (instance == null) {
                    instance = new ReqMessage();
                }
            }
        }
        return instance;
    }

    private final String key = "15d7a7182f4349c3ad06accdf66cf7b9";

    public String message(Map<String, Object> map, Context context) {
        String result = null;
        try {
            String userId = PreferencesUtils.getString(context, "userId", "");
            String token = PreferencesUtils.getString(context, "token", "");
            Map<String, Object> data = new HashMap<>();
            Map<String, Object> signData = new HashMap<>();
            if (!TextUtils.isEmpty(userId)) {
                map.put("userId", userId);
            }
            if (!TextUtils.isEmpty(token)) {
                map.put("token", token);
            }
            //客户端类型
            map.put("sysType", "1");
            //操作系统版本号
//            map.put("sysVersion", android.os.Build.VERSION.RELEASE);
            //App版本号
//            map.put("appVersion", AppUtils.getVerCode(context));
            //内部版本号
            map.put("inVersion", "1");
            //设备固件号
//            map.put("sysTerNo", NetWorkUtils.getIpAddress());
            //时间戳
            map.put("timestamp", new SimpleDateFormat("yyMMddHHmmss").format(Calendar.getInstance().getTime()));
            Gson gson = new GsonBuilder().serializeNulls().create();
            String sign = sign(map, key);
//            Logger.e(" sign = " + sign);
            signData.put("SIGN", sign);
            data.put("REQ_BODY", map);
            data.put("REQ_HEAD", signData);
            result = gson.toJson(data).toString();
            String mapJson =  gson.toJson(map);
            Logger.json(mapJson);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 获取加签串
     */
//    public static String getQueryString(Map<String, Object> map) {
//        ArrayList<String> list = new ArrayList<String>();
//        for (Map.Entry<String, Object> entry : map.entrySet()) {
//            list.add(entry.getKey() + "=" + entry.getValue() + "&");
//        }
//        int size = list.size();
//        if (size == 0) {
//            return "";
//        }
//        String[] arrayToSort = list.toArray(new String[size]);
//        Arrays.sort(arrayToSort, String.CASE_INSENSITIVE_ORDER);
//        StringBuilder sb = new StringBuilder();
//        for (int i = 0; i < size; i++) {
//            sb.append(arrayToSort[i]);
//        }
//        return sb.deleteCharAt(sb.length() - 1).toString();
//    }
    public static String getQueryString(Map<String, Object> map) {
        if (map == null) {
            return "";
        }

        int size = map.keySet().size();

        if (size == 0) {
            return "";
        }

        String[] keysArr = map.keySet().toArray(new String[size]);
        Arrays.sort(keysArr, String.CASE_INSENSITIVE_ORDER);

        StringBuilder sb = new StringBuilder();
        for (int i = 0; i < size; i++) {
            String key = keysArr[i];
            Object value = map.get(key);
            if (value == null || "".equals(value.toString())) {
                continue;
            }
            sb.append(key).append("=").append(value).append("&");
        }

        if (sb.length() == 0) {
            return "";
        }

        return sb.deleteCharAt(sb.length() - 1).toString();
    }

    /**
     * 签名
     */
    public static String sign(Map<String, Object> map, String key) {
        String result = getQueryString(map);
        result += "&key=" + key;
        result = RMD5.encryption(result).toUpperCase();
        return result;
    }
}
